package com.example.dicomviewer;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.dicomviewer.core.Config;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadActivity extends AppCompatActivity {
    //    private static final String serverIP = "192.168.43.121:8888";
    private static final String TAG = "DownloadActivity";
    private String fileNameOfDownload = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //如果是手动创建的活动，一定记得绑定布局
        setContentView(R.layout.activity_download);
        downloadFileNames();
    }

    private void downloadFileNames() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 构建GET方法的请求
                    Request request = new Request.Builder()
                            .url("http://" + Config.getServerIP() + "/series/all")
                            .build();
                    // 发起请求
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    // 显示数据
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showNames(responseData);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private ArrayList<String> parseJSONWithJSONObject(String jsonData) {
        Log.d(TAG, jsonData);
        ArrayList<String> list = new ArrayList<String>();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                list.add(jsonArray.getString(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private void showNames(String responseData) {
        ArrayList<String> arrayList = parseJSONWithJSONObject(responseData);
        String[] adapterData = arrayList.toArray(new String[0]);
        Log.d(TAG, "adapterData: " + adapterData.toString());
        ListView listView = (ListView) findViewById(R.id.list_view);
        Log.d(TAG, "ListView : " + listView);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, adapterData));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int pos,
                                    long id) {
                // TODO Auto-generated method stub
                Log.d(TAG, "onItemClick : " + adapterData[pos]);
                Intent intent = new Intent();
                intent.putExtra("name", adapterData[pos]);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        setListViewHeightBasedOnChildren(listView);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

}